function xend = terminalvalue(chistart,sint,xstart,p)

% compute log(chi_sstart)
logchistart = log(chistart);

% solve differential equation
[sgrid,logchix] = ode45(@(s,logchix) diffeqchi(s,logchix,p),sint,[logchistart xstart]);

% bound terminal value between -1 and 2
if (min(isfinite(logchix(:,2)))==0 || numel(sgrid)<numel(sint)) && (sint(1)<sint(2))
    xend = 2;
elseif (min(isfinite(logchix(:,2)))==0 || numel(sgrid)<numel(sint)) && (sint(1)>sint(2))
    xend = -1;
else
    xend = max(-1,min(2,logchix(end,2)));
end

end